package com.example.presentshopping.ui.custom;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ObjectUtils;
import com.example.presentshopping.R;
import com.example.presentshopping.config.bean.AreaDataSsqEntity;
import com.example.presentshopping.config.bean.CityModel;
import com.example.presentshopping.config.bean.DistrictModel;
import com.example.presentshopping.config.bean.ProvinceModel;
import com.example.presentshopping.ui.custom.city.ArrayWheelAdapter;
import com.example.presentshopping.ui.custom.city.OnWheelChangedListener;
import com.example.presentshopping.ui.custom.city.WheelView;
import com.example.presentshopping.utils.tool.unit.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LoacationView {
    private static PopupWindow mPopTime;
    public static String jsonData = "";
    public Context context;
    private AreaDataSsqEntity areaDataEntity;
    private WheelView mViewProvince, mViewCity, mViewDistrict;
    private boolean isSecondLinage;
    protected String[] mProDatas, proAreaId;
    private View emptyView, mAreaPicker;
    public static String  mCurrentProviceName, mCurrentCityName, mCurrentDistrictName = "";
    protected Map<String, String[]> mCitisDatasMap = new HashMap(), cityAreaIdMap = new HashMap<>();
    protected Map<String, String[]> mDistrictDatasMap = new HashMap(), distAreaIdMap = new HashMap<>();
    private int currentProPosition, currentCityPosition, currentDisPosition;
    private int newProPosition, newCityPosition, newDisPosition, visibility;
    private String mCurProValue, mCurCityValue, mCurDistValue;
    private  TextView loactlivew;
    private String industry = null;  // 行业
    private String subIndustry = null;  // 子行业
    private boolean currProvice = false;
    public LoacationView(Context context , TextView loactlivew ,View view, View view_all) {
        this.context = context;
        this.loactlivew = loactlivew;
        showLoacationView(view, view_all );
    }

    public  void showLoacationView(View view, View view_all) {
        jsonData = StringUtils.readAssetsTxt(context, "json_ssq");
        initAreaView();
        propetyAnim(view_all, 0, 0.2f, 0.5f, 0.7f, 0.9f, 1);
        showTimePicker(view, mAreaPicker , view_all);

    }

    public static void showTimePicker(View parent, final View view,  final View iv_all) {
        mPopTime = new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopTime.setOutsideTouchable(true);
        mPopTime.setFocusable(true); // 这个很重要,涉及返回键能否取消mPop！
        mPopTime.setBackgroundDrawable(new ColorDrawable(0));
        //mPop.setAnimationStyle(R.style.AndroidImageSlider_Attractive_Rect_Blue);
        mPopTime.setAnimationStyle(R.style.ActionSheetDialogAnimation);
        mPopTime.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        mPopTime.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                propetyAnim(iv_all, 1, 0.9f, 0.7f, 0.5f, 0.2f, 0);
                mPopTime = null;
            }
        });
        mPopTime.showAsDropDown(parent);
    }

    /**
     * 半透明背景出现的动画
     */
    private static void propetyAnim(View iv, float... values) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(iv, "alpha", values);
        animator.setDuration(500);
        animator.setRepeatCount(0);
        animator.start();
        iv.setVisibility(View.VISIBLE);
    }

    private  void initAreaView() {
        initAreaPicker();
        initProvinceDatas();
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        if (!isSecondLinage) mViewDistrict.setVisibleItems(7);
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<>(context, mProDatas, 15, 14));
//        updatePro();
        updateCities();
        updateAreas();
    }

    /**
     * 初始化控件
     */
    private void initAreaPicker() {  // 滑轮界面
        mAreaPicker = View.inflate(context, R.layout.picker_area_layout33, null);
        mViewProvince = ((WheelView) mAreaPicker.findViewById(R.id.id_province));
        mViewCity = ((WheelView) mAreaPicker.findViewById(R.id.id_city));
        mViewDistrict = ((WheelView) mAreaPicker.findViewById(R.id.id_area));
        if (isSecondLinage) mViewDistrict.setVisibility(View.GONE); //
        mViewProvince.addChangingListener(onChanged);
        mViewCity.addChangingListener(onChanged);
        mViewDistrict.addChangingListener(onChanged);

        RelativeLayout tv_cancelStart = ((RelativeLayout) mAreaPicker.findViewById(R.id.tv_cancel));
        RelativeLayout tv_confirmStart = ((RelativeLayout) mAreaPicker.findViewById(R.id.tv_confirm));
        tv_cancelStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopTime != null) {
                    mPopTime.dismiss();

                }
            }
        });
        tv_confirmStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentProPosition = newProPosition;
                currentCityPosition = newCityPosition;
                currentDisPosition = newDisPosition;

                mCurrentProviceName = mProDatas[currentProPosition];
                if (isSecondLinage) {
                    if (!mCurrentProviceName.equals("不限"))
                       mCurrentCityName = ((String[]) mCitisDatasMap.get(mCurrentProviceName))[currentCityPosition];
                } else {
                    if (!mCurrentProviceName.equals("全国"))
                      mCurrentCityName = ((String[]) mCitisDatasMap.get(mCurrentProviceName))[currentCityPosition];
                }
                String[] disNames = ((String[]) mDistrictDatasMap.get(mCurrentCityName));
                if (disNames != null && disNames.length > currentDisPosition) {
                  mCurrentDistrictName = disNames[currentDisPosition];
                } else {
                    mCurrentDistrictName = "";
                }

                // 设置二级或者三级
                List<AreaDataSsqEntity.DataBean> data = areaDataEntity.getData();
                int size = data.size();
                if (isSecondLinage) {
                    // 二级
                    if (mCurrentProviceName.equals("不限")) {
                        mCurrentCityName = "";
                    }
                    loactlivew.setText(mCurrentProviceName + "  " + mCurrentCityName);
                    if (ObjectUtils.isEmpty(data)) {
                        return;
                    }
                    industry = null;// 清除之前数据
                    subIndustry = null;
                    for (int i = 0; i < size; i++) {
                        if (data.get(i).getLabel().equals(mCurrentProviceName)) {
                            Log.d("第一的CODe", data.get(i).getValue());
                            industry = data.get(i).getValue();
                        }
                        List<AreaDataSsqEntity.DataBean.ChildrenBeanX> children = data.get(i).getChildren();
                        if (ObjectUtils.isEmpty(children)) {
                            continue;
                        }
                        int size1 = children.size();
                        for (int j = 0; j < size1; j++) {
                            if (children.get(j).getLabel().equals(mCurrentCityName)) {
                                Log.d("第二级CODe", children.get(j).getValue());
                                subIndustry = children.get(j).getValue();
                            }
                        }
                    }


                } else {
                    if (mCurrentProviceName.equals("全国")) {
                        mCurrentCityName = "";
                        mCurrentDistrictName = "";
                    }
                    loactlivew.setText(mCurrentProviceName + "  " + mCurrentCityName + "  " + mCurrentDistrictName);

                    /** 查询省市区的 value  */
                    mCurCityValue = null;// 清除之前数据
                    mCurProValue = null;
                    mCurDistValue = null;
                    if (ObjectUtils.isEmpty(data)) {
                        return;
                    }
                    for (int i = 0; i < size; i++) {
                        if (data.get(i).getLabel().equals(mCurrentProviceName)) {
                            Log.d("省的CODe", data.get(i).getValue());
                            mCurProValue = data.get(i).getValue();
                            currProvice = true;
                        } else currProvice = false;
                        List<AreaDataSsqEntity.DataBean.ChildrenBeanX> children = data.get(i).getChildren();
                        if (ObjectUtils.isEmpty(children)) {

                            continue;
                        }
                        int size1 = children.size();
                        for (int j = 0; j < size1; j++) {
                            if (children.get(j).getLabel().equals(mCurrentCityName)) {
                                Log.d("市的CODe", children.get(j).getValue());
                                mCurCityValue = children.get(j).getValue();
                            }
                            List<AreaDataSsqEntity.DataBean.ChildrenBeanX.ChildrenBean> children1 = children.get(j).getChildren();
                            if (ObjectUtils.isEmpty(children1)) {
                                continue;
                            }
                            int size2 = children1.size();
                            for (int k = 0; k < size2; k++) {
                                if (children1.get(k).getLabel().equals(mCurrentDistrictName) && currProvice) {
                                    Log.d("区的CODe", children1.get(k).getValue());
                                    mCurDistValue = children1.get(k).getValue();
                                }
                            }
                        }
                    }

                }

                if (mPopTime != null) {
                    mPopTime.dismiss();
                }
            }
        });
    }

    /**
     * 解析数据
     */
    protected void initProvinceDatas() {
        List provinceModelList = new ArrayList<ProvinceModel>();
        areaDataEntity = JSON.parseObject(jsonData.trim(), AreaDataSsqEntity.class);
        if (areaDataEntity == null) {
            return;
        }
        List<AreaDataSsqEntity.DataBean> chinaBean = areaDataEntity.getData();
        if (chinaBean.size() == 0) {
            return;
        }
        for (int j = 0; j < chinaBean.size(); j++) { // 省份
            List<CityModel> cityModelList = new ArrayList<>();
            ProvinceModel provinceModel = new ProvinceModel();
            AreaDataSsqEntity.DataBean childBean = chinaBean.get(j);
            provinceModel.setName(childBean.getLabel());
            String value = childBean.getValue();
            if (TextUtils.isEmpty(value)) value = "0";
            provinceModel.setArea_id(value);
            if (childBean.getChildren().size() == 0) {
                provinceModelList.add(provinceModel);
                continue;
            }
            for (int k = 0; k < childBean.getChildren().size(); k++) {  // 市
                List<DistrictModel> districtModelList = new ArrayList<>();
                CityModel cityModel = new CityModel();
                AreaDataSsqEntity.DataBean.ChildrenBeanX childCityBean = childBean.getChildren().get(k);
                cityModel.setName(childCityBean.getLabel());
                String value1 = childCityBean.getValue();
                if (TextUtils.isEmpty(value1)) value1 = "0";
                cityModel.setArea_id(value1);

                if (!isSecondLinage) {
                    if (childCityBean.getChildren() == null) {
                        cityModelList.add(cityModel);
                        continue;
                    }
                    for (int m = 0; m < childCityBean.getChildren().size(); m++) { // 区
                        DistrictModel districtModel = new DistrictModel();
                        AreaDataSsqEntity.DataBean.ChildrenBeanX.ChildrenBean childDisBean = childCityBean.getChildren().get(m);
                        String value2 = childDisBean.getValue();
                        if (TextUtils.isEmpty(value2)) value2 = "0";
                        districtModel.setArea_id(value2);
                        districtModel.setName(childDisBean.getLabel());
                        districtModelList.add(districtModel);
                    }
                }
                cityModel.setDistrictList(districtModelList);
                cityModelList.add(cityModel);
            }
            provinceModel.setCityList(cityModelList);
            provinceModelList.add(provinceModel);
        }

        List cityDataList;
        if (provinceModelList != null && !provinceModelList.isEmpty()) {
            this.mCurrentProviceName = ((ProvinceModel) provinceModelList.get(0)).getName();
            List i = ((ProvinceModel) provinceModelList.get(0)).getCityList();
            if (i != null && !i.isEmpty()) {
                this.mCurrentCityName = ((CityModel) i.get(0)).getName();
                cityDataList = ((CityModel) i.get(0)).getDistrictList();
                if (cityDataList != null)
                    this.mCurrentDistrictName = ((DistrictModel) cityDataList.get(0)).getName();
            }
        }
        this.mProDatas = new String[provinceModelList.size()];
        this.proAreaId = new String[provinceModelList.size()];

        for (int j = 0; j < provinceModelList.size(); ++j) {
            mProDatas[j] = ((ProvinceModel) provinceModelList.get(j)).getName();
            proAreaId[j] = ((ProvinceModel) provinceModelList.get(j)).getArea_id();
            List cityList = ((ProvinceModel) provinceModelList.get(j)).getCityList();
            if (cityList == null) {
                continue;
            }
            String[] cityNames = new String[cityList.size()];
            String[] cityAreaIds = new String[cityList.size()];
            for (int k = 0; k < cityList.size(); ++k) {
                cityNames[k] = ((CityModel) cityList.get(k)).getName();
                cityAreaIds[k] = ((CityModel) cityList.get(k)).getArea_id();
                List districtList = ((CityModel) cityList.get(k)).getDistrictList();
                if (districtList == null) {
                    continue;
                }
                String[] distrinctNameArray = new String[districtList.size()];
                String[] distrinctAreaId = new String[districtList.size()];
                DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                for (int m = 0; m < districtList.size(); ++m) {
                    DistrictModel districtModel = new DistrictModel(((DistrictModel) districtList.get(m)).getName(), ((DistrictModel) districtList.get(m)).getZipcode(), ((DistrictModel) districtList.get(m)).getArea_id());
                    distrinctArray[m] = districtModel;
                    distrinctNameArray[m] = districtModel.getName();
                    distrinctAreaId[m] = districtModel.getArea_id();
                }
                this.mDistrictDatasMap.put(cityNames[k], distrinctNameArray);
                this.distAreaIdMap.put(cityNames[k], distrinctAreaId);
            }
            this.mCitisDatasMap.put(((ProvinceModel) provinceModelList.get(j)).getName(), cityNames);
            this.cityAreaIdMap.put(((ProvinceModel) provinceModelList.get(j)).getName(), cityAreaIds);
        }
    }

    /**
     * 设置市级数据
     */
    private void updateCities() {
        int pCurrent = this.mViewProvince.getCurrentItem();
        this.mCurrentProviceName = this.mProDatas[pCurrent];
        String[] cities = (String[]) this.mCitisDatasMap.get(this.mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }

        this.mViewCity.setViewAdapter(new ArrayWheelAdapter(context, cities, 15, 14));
        this.mViewCity.setCurrentItem(0);
        this.updateAreas();
    }

    /**
     * 设置区级数据
     */
    private void updateAreas() {
        if (isSecondLinage) return;

        int pCurrent = this.mViewCity.getCurrentItem();
        if (!this.mCurrentProviceName.equals("全国")) {
//            this.mCurrentCityName = "0";
            this.mCurrentCityName = ((String[]) this.mCitisDatasMap.get(this.mCurrentProviceName))[pCurrent];
        }
//        this.mCurrentCityName = ((String[]) this.mCitisDatasMap.get(this.mCurrentProviceName))[pCurrent];
        String[] areas = this.mDistrictDatasMap.get(this.mCurrentCityName);

        if (areas == null || this.mCurrentProviceName.equals("全国")) {
            areas = new String[]{""};
        }
        this.mViewDistrict.setViewAdapter(new ArrayWheelAdapter(context, areas, 15, 14));
        this.mViewDistrict.setCurrentItem(0);
    }



   public OnWheelChangedListener  onChanged =   new OnWheelChangedListener() {
        @Override
        public void onChanged(WheelView wheel, int oldValue, int newValue) {
            if (wheel == mViewProvince) {
                newProPosition = newValue;
                updateCities();
            } else if (wheel == mViewCity) {
                newCityPosition = newValue;
                updateAreas();
            } else if (!isSecondLinage && wheel ==mViewDistrict) {
                newDisPosition = newValue;
            }
        }
    };
}
